//
//  SERegistrationHospitalController.swift
//  SmartEyeForPatient
//
//  Created by qdsg on 2021/4/2.
//

import UIKit
import MJRefresh

class SEHospitalListViewController: SEBaseViewController {

    @IBOutlet weak var tableView: UITableView! {
        didSet {
            tableView.tableFooterView = UIView()
            tableView.separatorColor = UIColor.init(hex: "EBECF0")
            tableView.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            tableView.mj_header = SERefreshHeader {
                self.loadNewData()
            }
            tableView.mj_footer = SERefreshFooter {
                self.loadMoreData()
            }
            tableView.register(UINib(nibName: SEHospitalListExamineCell.className,bundle: nil), forCellReuseIdentifier: SEHospitalListExamineCell.reuseId)
            tableView.register(UINib(nibName: SEHospitalListRegistraionCell.className,bundle: nil), forCellReuseIdentifier: SEHospitalListRegistraionCell.reuseId)
        }
    }

    @IBOutlet weak var searchBar: UISearchBar! {
        didSet {
            searchBar.delegate = self
        }
    }

    var viewModel = SEHospitalListViewModel()

    init(with type: SEHospitalListType) {
        viewModel.hospitalListType = type
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = viewModel.hospitalListType.title
        self.beginRefresh()
        self.getLocation()
    }

    override func setupUI() {
        super.setupUI()

        viewModel.updateData = { [weak self] (status) in
            self?.endRefreshing()
            switch status {
            case .success:
                self?.tableView.reloadData()
            case .auth(let msg):
                self?.presentLoginViewController(selector: #selector(self?.beginRefresh)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        searchBarBecomeFirstResponse(searchBar)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        searchBarResignFirstResponse(searchBar)
    }

    func searchBarBecomeFirstResponse(_ searchBar: UISearchBar) {
        if !(searchBar.text?.isEmpty ?? true) {
            searchBar.becomeFirstResponder()
            navigationController?.setNavigationBarHidden(true, animated: true)
        }
    }

    func searchBarResignFirstResponse(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        searchBar.showsCancelButton = false
        navigationController?.setNavigationBarHidden(false, animated: true)
    }

    func getLocation() {
        SELocationManager.shared.startlocating(self) { (model) in
            guard let model = model else { return }
            self.viewModel.latitude = model.latitude
            self.viewModel.longtitude = model.longitude
            self.loadNewData()
        }
    }

    private func pushToRegistrationDepartment() {
        let vc = SERegistrationTypeController(with: viewModel.selectedItem)
        navigationController?.pushViewController(vc, animated: true)
    }

    private func pushToExamineReserve() {
        let vc = SEExamineReserveViewController(with: viewModel.selectedItem, checkSource: 1)
        navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK: - UITableViewDataSource,UITableViewDelegate

extension SEHospitalListViewController: UITableViewDataSource, UITableViewDelegate {

    // MARK: - UITableViewDataSource

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch viewModel.hospitalListType {
        case .registration:
            let cell = tableView.dequeueReusableCell(withIdentifier: SEHospitalListRegistraionCell.reuseId, for: indexPath) as! SEHospitalListRegistraionCell
            cell.updateCell(model: viewModel.listItem(indexPath: indexPath))
            return cell
        case .examine:
            let cell = tableView.dequeueReusableCell(withIdentifier: SEHospitalListExamineCell.reuseId, for: indexPath) as! SEHospitalListExamineCell
            cell.updateCell(model: viewModel.listItem(indexPath: indexPath))
            return cell
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.models.count
    }

    // MARK: - UITableViewDelegate

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return viewModel.hospitalListType.heightForRow
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        viewModel.selectedItem = viewModel.listItem(indexPath: indexPath)
        if viewModel.hospitalListType == .registration {
            pushToRegistrationDepartment()
        }
        if viewModel.hospitalListType == .examine {
            pushToExamineReserve()
        }
    }
}

// MARK: - UISearchBarDelegate

extension SEHospitalListViewController: UISearchBarDelegate {
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        view.endEditing(true)
        let cancelBtn = searchBar.value(forKey: "cancelButton") as? UIButton
        cancelBtn?.isEnabled = true
        viewModel.hospitalName = searchBar.text!
        loadNewData()
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        view.endEditing(true)
        searchBar.text = ""
        searchBar.setShowsCancelButton(false, animated: true)
        navigationController?.setNavigationBarHidden(false, animated: true)
        viewModel.hospitalName = searchBar.text!
        loadNewData()
    }

    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        searchBar.setShowsCancelButton(true, animated: true)
        navigationController?.setNavigationBarHidden(true, animated: true)
    }

    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {

    }
}

// MARK: - APIRequest

extension SEHospitalListViewController {

    private func endRefreshing() {
        tableView.se_footer_hidden = false
        tableView.endHeaderRefreshing()
        tableView.endFooterRefreshing(hasMore: viewModel.hasMore)
    }

    @objc private func beginRefresh() {
        tableView.mj_header?.beginRefreshing()
    }

    private func loadNewData() {
        viewModel.page = 1
        requestHospitalList()
    }

    private func loadMoreData() {
        viewModel.page += 1
        requestHospitalList()
    }

    private func requestHospitalList() {
        viewModel.requestHospitalList()
    }
}
